package org.apache.rocketmq.example.util;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageQueue;

public class RocketMQPrinter {

    // 颜色代码常量
    private static final String ANSI_RESET = "\u001B[0m";
    private static final String ANSI_GREEN = "\u001B[32m";
    private static final String ANSI_BLUE = "\u001B[34m";
    private static final String ANSI_YELLOW = "\u001B[33m";
    private static final String ANSI_CYAN = "\u001B[36m";
    private static final String ANSI_PURPLE = "\u001B[35m";

    /**
     * 美化打印SendResult信息
     */
    public static void printSendResult(SendResult sendResult) {
        if (sendResult == null) {
            System.out.println(ANSI_YELLOW + "SendResult is null" + ANSI_RESET);
            return;
        }

        // 打印标题
        printSeparator();
        System.out.println(ANSI_GREEN + "===== RocketMQ Send Result =====" + ANSI_RESET);
        printSeparator();

        // 打印基本信息
        System.out.printf(ANSI_BLUE + "Send Status: " + ANSI_RESET + "%s%n",
                formatStatus(sendResult.getSendStatus().name()));

        // 打印消息ID信息
        System.out.println(ANSI_CYAN + "\nMessage IDs:" + ANSI_RESET);
        System.out.printf("  %-20s: %s%n", "msgId", sendResult.getMsgId());
        System.out.printf("  %-20s: %s%n", "offsetMsgId", sendResult.getOffsetMsgId());

        // 打印消息队列信息
        MessageQueue mq = sendResult.getMessageQueue();
        if (mq != null) {
            System.out.println(ANSI_CYAN + "\nMessage Queue Info:" + ANSI_RESET);
            System.out.printf("  %-20s: %s%n", "Topic", mq.getTopic());
            System.out.printf("  %-20s: %s%n", "Broker Name", mq.getBrokerName());
            System.out.printf("  %-20s: %d%n", "Queue ID", mq.getQueueId());
            System.out.printf("  %-20s: %d%n", "Queue Offset", sendResult.getQueueOffset());
        }

        // 打印撤回信息
        if (sendResult.getRecallHandle() != null) {
            System.out.println(ANSI_CYAN + "\nRecall Info:" + ANSI_RESET);
            System.out.printf("  %-20s: %s%n", "Recall Handle", sendResult.getRecallHandle());
        }

        printSeparator();
        System.out.println();
    }

    /**
     * 格式化状态信息，根据状态显示不同颜色
     */
    private static String formatStatus(String status) {
        switch (status) {
            case "SEND_OK":
                return ANSI_GREEN + status + ANSI_RESET;
            case "FLUSH_DISK_TIMEOUT":
            case "FLUSH_SLAVE_TIMEOUT":
            case "SLAVE_NOT_AVAILABLE":
                return ANSI_YELLOW + status + ANSI_RESET;
            default:
                return ANSI_PURPLE + status + ANSI_RESET;
        }
    }

    /**
     * 打印分隔线
     */
    private static void printSeparator() {
        System.out.println(ANSI_BLUE + "----------------------------------------" + ANSI_RESET);
    }


}
